// @algorithm @lc id=100340 lang=cpp
// @title ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
    int strToInt(string str) {
        bool isPositive;
        bool isValid = false;
        int length = str.length();
        // 空字符串
        if (length == 0) {
            return 0;
        }
        int index = 0;
        // 去除前导空格，如果字符串里只有空格，则直接返回0
        while (index < length && str[index] == ' ') {
            ++index;
        }
        if (index == length) {
            return 0;
        }
        // 确定正负号
        if (str[index] == '-' || str[index] == '+') {
            isPositive = str[index] == '+' ? true : false;
            ++index;
            if (index < length && str[index] >= '0' && str[index] <= '9') {
                isValid = true;
            }
        }
        else if (str[index] >= '0' && str[index] <= '9') {
            isPositive = true;
            isValid = true;
        }
        else {
            isValid = false;
        }
        if (!isValid) {
            return 0;
        }
        long ans = isPositive ? str[index++] - '0' : -(str[index++] - '0');
        while (index < length && str[index] >= '0' && str[index] <= '9') {
            ans = isPositive ? ans * 10 + (str[index++] - '0') : ans * 10 - (str[index++] - '0');
            if (ans > INT_MAX) {
                return INT_MAX;
            }
            if (ans < INT_MIN) {
                return INT_MIN;
            }
        }
        return (int)ans;
    }
};